package com.live.task;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.live.activity.R;
import com.live.adapter.LiveReviewSimpleAdapter;
import com.live.common.Constant;

public class LiveReview extends AsyncTask<Bundle, Integer, String> {
	private List<Map<String, Object>> liveReviewListAll = new ArrayList<Map<String, Object>>();

	private ListView reviewList;

	private Context context = null;

	public SharedPreferences store = null;

	public LiveReview(Context context, ListView reviewList) {
		this.context = context;
		this.reviewList = reviewList;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("Comment", "onPreExecute()  " + Thread.currentThread().getId());
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("Comment", "doInBackground... " + Thread.currentThread().getId());

		String url = Constant.SITE_URL + "live_review.php?matchId=" + params[0].getString("matchId");
		if (liveReviewListAll.size() > 0) {
			Map<String, Object> review = liveReviewListAll.get(0);
			String reviewId = (String) review.get("reviewId");
			url += "&reviewId=" + reviewId;
		}
		List<Map<String, Object>> liveReviewList = getMatchReview(url);
		liveReviewList.addAll(liveReviewListAll);
		liveReviewListAll = liveReviewList;

		publishProgress();
		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());
		// 用户登录判断
		store = context.getSharedPreferences(Constant.PREFS_NAME, 0);
		String userId = store.getString("userId", null);
		LiveReviewSimpleAdapter adapter = new LiveReviewSimpleAdapter(context, liveReviewListAll, R.layout.review_list,
				new String[] { "reviewUser", "reviewText", "reviewDate" }, new int[] { R.id.reviewUser,
						R.id.reviewText, R.id.reviewDate }, userId);

		reviewList.setAdapter(adapter);
		// NetActivity.this.setTitle("加载了  " + values[0] + "%");

	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		// tv.setText(result);
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
	}

	private List<Map<String, Object>> getMatchReview(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						JSONArray matches = new JSONObject(out).getJSONArray("results");
						for (int i = 0; i < matches.length(); i++) {
							Map<String, Object> map = new HashMap<String, Object>();

							map.put("id", matches.getJSONObject(i).get("id"));
							map.put("reviewId", matches.getJSONObject(i).get("reviewId"));
							map.put("reviewUser", matches.getJSONObject(i).get("reviewUser"));
							map.put("reviewUserPic", matches.getJSONObject(i).get("reviewUserPic"));
							map.put("reviewDate", matches.getJSONObject(i).get("updateDate"));

							String reviewText = (String) matches.getJSONObject(i).get("reviewText");
							reviewText = reviewText.replace("\\n", "\n");
							map.put("reviewText", reviewText);
							data.add(map);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	public boolean addMatchReview(String url, List<NameValuePair> postData) {
		HttpClient client = new DefaultHttpClient();

		// 提拱默认的HttpClient实现
		HttpPost httppost;
		try {
			httppost = new HttpPost(new URI(url));
			httppost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
			HttpResponse response = client.execute(httppost);

			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) {
				// 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						String result = new JSONObject(out).getString("results");

						if (Constant.SUCCESS.equals(result)) {

							// 提示评论发表成功
							Toast.makeText(context, "评论发表成功！", Toast.LENGTH_LONG).show();
							return true;
						} else {
							// 提示评论发表失败
							Toast.makeText(context, "评论发表失败！", Toast.LENGTH_LONG).show();
							return false;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean delMatchReview(String url) {
		HttpClient client = new DefaultHttpClient();

		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) {
				// 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						String result = new JSONObject(out).getString("results");

						if (Constant.SUCCESS.equals(result)) {

							// 提示评论发表成功
							Toast.makeText(context, R.string.delete_info, Toast.LENGTH_LONG).show();
							return true;
						} else {
							// 提示评论发表失败
							Toast.makeText(context, "评论删除失败！", Toast.LENGTH_LONG).show();
							return false;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}